package com.burgeon.backend.SHOPBACKEND.service.Impl;

import com.burgeon.backend.SHOP.service.SystemService;
import com.burgeon.backend.SHOPBACKEND.entity.WxChatImage;
import com.burgeon.backend.SHOPBACKEND.entity.recored.Relation;
import com.burgeon.backend.SHOPBACKEND.entity.vip.Employee;
import com.burgeon.backend.SHOPBACKEND.entity.vip.Vip;
import com.burgeon.backend.SHOPBACKEND.entity.weixin.TextMessage;
import com.burgeon.backend.SHOPBACKEND.mappers.AndroidMapper;
import com.burgeon.backend.SHOPBACKEND.mappers.MessageMapper;
import com.burgeon.backend.SHOPBACKEND.mappers.RecordMapper;
import com.burgeon.backend.SHOPBACKEND.mappers.WxUserMapper;
import com.burgeon.backend.SHOPBACKEND.push.UmengUtil;
import com.burgeon.backend.SHOPBACKEND.rest.weixin.FindVipByOpenId;
import com.burgeon.backend.SHOPBACKEND.rest.weixin.ModVipUnread;
import com.burgeon.backend.SHOPBACKEND.rest.weixin.VipAppCode;
import com.burgeon.backend.SHOPBACKEND.rest.weixin.findEmployeeById;
import com.burgeon.backend.SHOPBACKEND.service.AWechatService;
import com.burgeon.backend.SHOPBACKEND.service.ex.UploadException;
import com.burgeon.backend.SHOPBACKEND.websocket.WebSocketServer;
import com.burgeon.backend.Util.menu.WeChatInfo;
import com.burgeon.backend.Util.wechatUtil.*;
import com.burgeon.backend.WeChat.GetAccesToken;
import com.burgeon.backend.entity.Info;
import com.burgeon.backend.mappers.AccountMapper;
import com.burgeon.backend.service.WechatService;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * 微信与安卓导购的聊天
 */
@Service
public class AWechatServiceImpl implements AWechatService {
    @Autowired
    private MessageMapper messageMapper;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Resource
    private RedisUtil2 redisUtil2;

    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private SystemService systemService;
    @Autowired
    private WechatService wechatService;
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private AndroidMapper androidMapper;

   public static Session session;
    private final static Log log = LogFactory.getLog(AWechatService.class);
    @Autowired
    private GetAccesToken getAccesToken;


    /**
     * ERP修改是否有未读消息
     */
    public void  UpVipUnread(String openID,String unread,String type,String state,String content,Vip vip,String msgType,String token){
        Info info = GetInfo(token);
        //根据openId获取vip用户信息
//        FindVipByOpenId findVipByOpenId = new FindVipByOpenId(info.getUrl(), info.getAccount(),info.getPassword());
//        try {
//            Vip vip  = findVipByOpenId.getData(openID);
//            if(null != vip ) {
                ModVipUnread g = new ModVipUnread(info.getUrl(), info.getAccount(),info.getPassword());
                VipAppCode vipAppCode = new VipAppCode(info.getUrl(), info.getAccount(),info.getPassword());
                try {

                    g.getData(vip.getId(), unread);
                    log.info("修改erp的是否有未读消息状态修改为否了");
                    vipAppCode.getData(vip.getCardNo(), type, vip.getEmployeeName(), vip.getEmpId(), state, content);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if("Y".equals(unread)){
                    if(!"null".equals(vip.getEmployeeName())) {
                        UmengUtil umengUtil = new UmengUtil();
                        //华为通风道
                        String channel = "com.bojun.rfmapplication.activity.home.OrderListActivity";
                        //发送消息
                        //System.err.println("导购的手机号：" + employee.getPhone());
                        String extraType = "1";//1是消息
                        System.err.println(vip.getEmpPhone());
                        try {
                            if(msgType.equals("text")){
                                umengUtil.sendAndroidCustomizedcast(vip.getEmpPhone(),"phone",
                                        "微信消息", "来自顾客的消息", content, openID, channel, "1");
                            }else if (msgType.equals("miniprogrampage")){
                                umengUtil.sendAndroidCustomizedcast(vip.getEmpPhone(),"phone",
                                        "微信消息", "来自顾客的消息", "小程序消息", openID, channel, "1");
                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    }
            }


    }

//将消息存到erp
    public void CreteVipCode(String openId,String type,String employeeName,String hrOpenid,
                             String state,String content,String token) {
        Info info = GetInfo(token);
        //根据openId获取vip用户信息
        FindVipByOpenId findVipByOpenId = new FindVipByOpenId(info.getUrl(), info.getAccount(),info.getPassword());
        try {
            Vip vip = findVipByOpenId.getData(openId);
            VipAppCode vipAppCode = new VipAppCode(info.getUrl(), info.getAccount(),info.getPassword());
            try {
                vipAppCode.getData(vip.getCardNo(), type, employeeName, hrOpenid, state, content);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //从微信接收过来的文本消息
    private String AcceptTextWei(Info info,String fromUserName,String content,String createTime,
                               String msgType,String toUserName,String token){
        FindVipByOpenId findVipByOpenId = new FindVipByOpenId(info.getUrl(), info.getAccount(),
                info.getPassword());
        try {
            Vip vip = findVipByOpenId.getData(fromUserName);
            //System.err.println(vip);
            log.info("vip是否存在"+vip);
            if (null != vip){
                if(!"null".equals(vip.getEmpId())) {
                    // String unicode = EmojiUtil.escapeUnicode(content);
                    content = EmojiUtil.filterEmoji(content);
                    String websocket = content.replace("\\","\\\\");
                    String message = "{\"fromUserName\": \"" + fromUserName + "\",\"msgtype\": \"text\", \"text\": {\"content\": \"" + websocket + "\"}}";
//                          System.err.println(message);
                    String state = null;
                    try {
                        state = webSocketServer.sendtoUser(message, vip.getEmpId());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    createTime = formatTime(createTime);

                    if ("0".equals(state)) {
                        //消息存到erp
                        try {
                            //CreteVipCode(fromUserName,"发出",employee.getName(),employee.getId(),state,content);
                            //将消息存到数据库,发送成功
//                            recordMapper.InMessageRecord(fromUserName,vip.getEmpId(),content,createTime,state,vip.getEmpId(),"","");
                            //并修改erp状态，加未读消息标志Y
                            UpVipUnread(fromUserName,"N","发出",state,content,vip,msgType,token);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
//                        recordMapper.InMessageRecord(fromUserName,vip.getEmpId(),content,createTime,state,vip.getEmpId(),"","");
                        // 并修改erp状态，加未读消息标志Y
                        UpVipUnread(fromUserName,"Y","发出",state,content,vip,msgType,token);
                    }
                }else {
                    //没有关联的导购，怎么处理
                    System.err.println("没有导购信息");
                    //转发给微信客服系统
                    log.info("没有导购信息，转发给微信客服");
                    return weiKf(fromUserName,toUserName);

                }
            }else {
                System.err.println("vip信息为空");
                log.info("没有vip信息");
                //转发给微信客服系统
                log.info("没有导购信息，转发给微信客服");
                return weiKf(fromUserName,toUserName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //从微信接收过来的图片消息
    private String AcceptImageWei(Info info,String fromUserName,String picUrl,String createTime,
                                 String msgType,String toUserName,String token){
        FindVipByOpenId findVipByOpenId = new FindVipByOpenId(info.getUrl(), info.getAccount(),
                info.getPassword());
        try {
            Vip vip = findVipByOpenId.getData(fromUserName);
            //System.err.println(vip);
            log.info("vip是否存在"+vip);
            if (null != vip){
                if(!"null".equals(vip.getEmpId())) {
                    // String unicode = EmojiUtil.escapeUnicode(content);
//                    content = EmojiUtil.filterEmoji(content);
//                    String websocket = content.replace("\\","\\\\");
                    String message = "{\"fromUserName\": \"" + fromUserName + "\",\"msgtype\": \"image\", \"image\": {\"content\": \"" + picUrl + "\"}}";
//                          System.err.println(message);
                    String state = null;
                    try {
                        state = webSocketServer.sendtoUser(message, vip.getEmpId());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    createTime = formatTime(createTime);

                    if ("0".equals(state)) {
                        //消息存到erp
                        try {
                            //CreteVipCode(fromUserName,"发出",employee.getName(),employee.getId(),state,content);
                            //将消息存到数据库,发送成功
//                            recordMapper.InMessageRecord(fromUserName,vip.getEmpId(),"",createTime,state,vip.getEmpId(),"",picUrl);
                            //并修改erp状态，加未读消息标志Y
                            UpVipUnread(fromUserName,"N","发出",state,picUrl,vip,msgType,token);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                    } else {
//                        recordMapper.InMessageRecord(fromUserName,vip.getEmpId(),picUrl,createTime,state,vip.getEmpId(),"",picUrl);
                        // 并修改erp状态，加未读消息标志Y
                        UpVipUnread(fromUserName,"Y","发出",state,picUrl,vip,msgType,token);
                    }
                }else {
                    //没有关联的导购，怎么处理
                    System.err.println("没有导购信息");
                    //转发给微信客服系统
                    log.info("没有导购信息，转发给微信客服");
                    return weiKf(fromUserName,toUserName);

                }
            }else {
                System.err.println("vip信息为空");
                log.info("没有vip信息");
                //转发给微信客服系统
                log.info("没有导购信息，转发给微信客服");
                return weiKf(fromUserName,toUserName);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    //从微信过来的链接消息
    private String AcceptMiniprogrampage(Info info,String fromUserName,String AppId,String PagePath,
                                       String ThumbUrl,String ToUserName,String createTime,String msgType,String token){

        FindVipByOpenId findVipByOpenId = new FindVipByOpenId(info.getUrl(), info.getAccount(),info.getPassword());
        try {
            Vip vip = findVipByOpenId.getData(fromUserName);
            //System.err.println(vip);
            if (null != vip){
                if(!"null".equals(vip.getEmpId())) {

                    String message = "{\"fromUserName\": \"" + fromUserName + "\",\"msgtype\": \"miniprogrampage\", \"miniprogrampage\": {\"AppId\": \"" + AppId + "\" , \"PagePath\":\"" + PagePath + "\" , \"ThumbUrl\":\"" + ThumbUrl + "\" , \"ToUserName\":\"" + ToUserName + "\" }}";
                    String miniprogrampage = "{\"AppId\": \"" + AppId + "\" , \"PagePath\":\"" + PagePath + "\" , \"ThumbUrl\":\"" + ThumbUrl + "\" , \"ToUserName\":\"" + ToUserName + "\" }";
//                    MiniProgramPage miniProgramPage = new MiniProgramPage();
//                    miniProgramPage.setAppId(AppId);
//                    miniProgramPage.setPagePath(PagePath);
//                    miniProgramPage.setThumbUrl(ThumbUrl);
//                    miniProgramPage.setToUserName(ToUserName);

                    String state = null;
                    try {
                        state = webSocketServer.sendtoUser(message, vip.getEmpId());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    createTime = formatTime(createTime);

                    if ("0".equals(state)) {
                        //消息存到erp
                        try {
                            //CreteVipCode(fromUserName,"发出",employee.getName(),employee.getId(),state,content);
                            //将消息存到数据库,发送成功
//                            recordMapper.InMiniProgramPageRecord(fromUserName,vip.getEmpId(),"",createTime,state,vip.getEmpId(),miniprogrampage,"");
                            //并修改erp状态，加未读消息标志Y
                            UpVipUnread(fromUserName,"N","发出",state,miniprogrampage,vip,msgType,token);
                        } catch (Exception e) {
                            e.printStackTrace();
                            log.error(e.getMessage());
                        }

                    } else {
//                        recordMapper.InMessageRecord(fromUserName,vip.getEmpId(),"",createTime,state,vip.getEmpId(),miniprogrampage,"");
                        // 并修改erp状态，加未读消息标志Y
                        UpVipUnread(fromUserName,"Y","发出",state,miniprogrampage,vip,msgType,token);

                    }
                }else {
                    //没有关联的导购，怎么处理
                    System.err.println("没有导购信息");
                    log.info("没有导购信息，转发给微信客服");
                    return weiKf(fromUserName,ToUserName);
                    //发送给微信客服系统
//                          <xml>
//                          <ToUserName><![CDATA[touser]]></ToUserName>
//                          <FromUserName><![CDATA[fromuser]]></FromUserName>
//                          <CreateTime>1399197672</CreateTime>
//                          <MsgType><![CDATA[transfer_customer_service]]></MsgType>
//                          </xml>

                }
            }else {
                log.info("没有导购信息，转发给微信客服");
                return weiKf(fromUserName,ToUserName);

            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 小程序接受到微信接口数据
     * @param response
     * @return
     */
    public String acceptMessage(Map<String, String> requestMap, HttpServletResponse response,String token) {
//        {CreateTime=1548042266, Event=user_enter_tempsession, ToUserName=gh_e6198220cbff,
//                FromUserName=oZvme4q2Oi7Dz3FChXc43kqw28, MsgType=event, SessionFrom=wxapp}
        String respMessage = "";
        try {
            // xml请求解析
           // Map<String, String> requestMap = MessageUtil.parseXml(request);
           // Map<String, String> requestMap = WechatMessageUtil.xmlToMap(request);
            log.info(">>>>>>>>>>>>>"+requestMap);
            // 发送方帐号（open_id）
            String fromUserName = requestMap.get("FromUserName");
            // 公众帐号
            String toUserName = requestMap.get("ToUserName");
            // 消息类型
            String msgType = requestMap.get("MsgType");

            String Event = requestMap.get("Event"); //user_enter_tempsession
            //SCAN 为扫描信息  VIEW 公众号底部点击事件

            String createTime =requestMap.get("CreateTime");

            log.info("fromUserName = "+fromUserName+" , ToUserName = "+toUserName+ " , msgType = "+msgType);

            Info info = GetInfoIsApp(token);//根据token去查询是否App注册

            StringBuffer contentMsg = new StringBuffer();
            String html = "https://xxxxx.cn/index/wechat/index.html?oid="+fromUserName;
            String url = "☞ <a href=\""+html+"\">点击跳转</a>";
            //公众号关注事件消息
            if(msgType.equals("event")){
                System.err.println("点击进入");
                log.info("点击进入客服");

                if(Event.equals("user_enter_tempsession")){
                    if (null == info){
                        //转发给微信客服
                        log.info("这个公司没有App，转发给微信客服");
                        return weiKf(fromUserName,toUserName);
                    }

                }
            }else if(msgType.equals("text")){
                log.info("公众号接受文字..........");
                String content = requestMap.get("Content");//是否获取的是消息内容
                //System.err.println(content);
                //把它发送给安卓
                String re = AcceptTextWei(info,fromUserName,content,createTime,msgType,toUserName,token);
                if (!"null".equals(re)){
                    return re;
                }

            }else if(msgType.equals("image")){
                log.info("公众号接受图片..........");
                String picUrl = requestMap.get("PicUrl");
                log.info("图片"+picUrl);
                String re = AcceptImageWei(info,fromUserName,picUrl,createTime,msgType,toUserName,token);

                if (!"null".equals(re)){
                    return re;
                }
            }else if (msgType.equals("miniprogrampage")){//微信小程序发过来的链接
                log.info("公众号接受商品链接..........");
                String AppId = requestMap.get("AppId");
                String PagePath = requestMap.get("PagePath");
                String ThumbUrl = requestMap.get("ThumbUrl");
                //String ToUserName = requestMap.get("ToUserName");
                String weiKf = AcceptMiniprogrampage(info,fromUserName,AppId,PagePath,ThumbUrl,toUserName,
                        createTime,msgType,token);
                if(!"null".equals(weiKf)){
                    return weiKf;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return respMessage;
    }

    /**
     * 接受企业微信的文本消息
     * @param context
     * @param openId
     * @param daoId
     * @param token
     */
    @Override
    public void messCopWeChat(String context, String openId, String daoId, String token) {
        Info info = GetInfo(token);
        String touser=openId;
        String accessToken = systemService.GetAccesToken(token);
        //发送给微信
        WeXinHuiFu.sendTextMessageToUser(context,touser,accessToken);
        Date d = new Date();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time= sd.format(d);
//        recordMapper.InMessageRecord(daoId,openId,context,time,"0",daoId,"","");
        findEmployeeById findEmployeeById = new findEmployeeById(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            Employee employee = findEmployeeById.getData(daoId);
            if(null!=employee){
                //存到erp
                CreteVipCode(openId,"接收",employee.getName(),daoId,"0",context,token);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //转发给微信客服
    private String weiKf(String fromUserName,String toUserName){
        TextMessage textMessage = new TextMessage();
        textMessage.setMsgType("transfer_customer_service");
        textMessage.setToUserName(fromUserName);
        textMessage.setFromUserName(toUserName);
        textMessage.setCreateTime(System.currentTimeMillis());
        String respMessage = WechatMessageUtil.textMessageToXml(textMessage);
        //System.err.println(respMessage);
        log.info("转发至微信小程序客服系统"+respMessage);
        return respMessage;
    }


    private Info GetInfo(String token) {
        return accountMapper.GetAccData(token);
    }
    private Info GetInfoIsApp(String token){
        return accountMapper.GetAccIsApp(token);
    }

    /**
     * 将从安卓获取来的消息发送给微信文本
     * @param openId
     * @throws UnsupportedEncodingException
     */
    public void messAndroid(String context,String openId,String daoId){
       // System.err.println(daoId);
        Info info = GetInfo(WeChatInfo.token);
        String touser=openId;
        //String accessToken = getAccesToken.GetAccesToken(WeChatInfo.token);
        String accessToken = systemService.GetAccesToken(WeChatInfo.token);
//        String accessToken = wechatService.GetAccesToken(WeChatInfo.token);
        //System.err.println(accessToken);
        //发送给微信
        WeXinHuiFu.sendTextMessageToUser(context,touser,accessToken);
        Date d = new Date();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time= sd.format(d);
        // messageMapper.InDaoMessage(context,touser,daoId,time);
//        recordMapper.InMessageRecord(daoId,openId,context,time,"0",daoId,"","");
        findEmployeeById findEmployeeById = new findEmployeeById(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            Employee employee = findEmployeeById.getData(daoId);
            if(null!=employee){
//                CreteVipCode(openId,"接收",employee.getName(),daoId,"0",context);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 发送图片
     * @param context
     * @param openId
     * @param daoId
     */
    public void messAndroidImage(String context,String openId,String daoId){

        Info info = GetInfo(WeChatInfo.token);
        String touser=openId;
        String accessToken = systemService.GetAccesToken(WeChatInfo.token);
        //发送给微信
        WeXinHuiFu.sendPicOrVoiceMessageToUser(context,touser,accessToken);
        Date d = new Date();
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time= sd.format(d);
        // messageMapper.InDaoMessage(context,touser,daoId,time);
        String imgUrl = androidMapper.getWeChatImage(context,WeChatInfo.token);
//        recordMapper.InMessageRecord(daoId,openId,"",time,"0",daoId,"",imgUrl);
        findEmployeeById findEmployeeById = new findEmployeeById(info.getUrl(),info.getAccount(),info.getPassword());
        try {
            Employee employee = findEmployeeById.getData(daoId);
            if(null!=employee){
//                CreteVipCode(openId,"接收",employee.getName(),daoId,"0",imgUrl);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 上传微信聊天图片
     * @param file
     * @param
     * @return
     */
    public WxChatImage upWeChatImage(MultipartFile file,String token){
        if (null == file || file.isEmpty()) {
            System.out.println("文件为空");
            throw new UploadException("文件为空");
        }else if(null == token || token.isEmpty()){
            throw new UploadException("客户标识为空");
        }

        String accessToken = systemService.GetAccesToken(token);
//        String fileName = file.getName();
        String fileName = file.getOriginalFilename(); //文件名
//        System.err.println(fileName);
        String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名
//        //http://lfwd.cloudsmicro.com/img/mgg-shop/2.png
        String filePath = "//root//code//img//" + token + "//wxUploadImg//"; // 上传后的路径
        fileName =fileName.substring(0,fileName.lastIndexOf("."))+suffixName; // 新文件名
        String url ="http://lfwd.cloudsmicro.com/img/"+token+"/wxUploadImg/"+fileName;
        filePath=filePath+fileName;

        saveFile(file,filePath);
        WxChatImage wxChatImage = new WxChatImage();
        try {
            String mediaId = MediaUtil.upload(accessToken,filePath,"image");

            wxChatImage.setMediaId(mediaId);
            wxChatImage.setUrkl(url);
            androidMapper.insertWeChatImage(mediaId,url,token);

        } catch (IOException e) {
            e.printStackTrace();
        }
        return wxChatImage;
    }

    //保存文件
    private void saveFile(MultipartFile multipartFile,String filePath) {
        File dest = new File(filePath);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        }
    }
    public String getAccount(String url){
        System.err.println("IP穿"+url);
        String token = androidMapper.GetTokenByUrl(url);
        System.err.println(token);
        String account = androidMapper.GetTokenByToken(token);
        System.err.println(account);
        return account;

    }


    /***
     * 从微信接收消息
     * @param request
     * @return
     * @throws UnsupportedEncodingException
     */
    public String messRequest(HttpServletRequest request, HttpSession session) throws UnsupportedEncodingException {
        request.setCharacterEncoding("UTF-8");
        Map<String, String> map = WechatMessageUtil.xmlToMap(request);
        //  System.err.println(map);
        //log.info(map);
        // 发送方帐号（一个OpenID）
        String fromUserName = map.get("FromUserName");
        // 开发者微信号
        String toUserName = map.get("ToUserName");
        session.setAttribute("openId",fromUserName);
        // 消息类型
        String msgType = map.get("MsgType");
        //System.err.println(msgType);
        // 消息创建时间
        String createTime =map.get("CreateTime");
        //System.err.println(createTime);
        // 默认回复一个"success"
        String responseMessage = "success";

        Info info = GetInfo(WeChatInfo.token);

        if (WechatMessageUtil.MESSAGE_TEXT.equals(msgType)) {// 文本消息
            String content = map.get("Content");//是否获取的是消息内容

            TextMessage textMessage = new TextMessage();
            textMessage.setFromUserName(fromUserName);//发送者的openid
            textMessage.setContent(content);//发送的信息

            //把它发送给安卓
            //从数据库根据用户openid获取导购id
            //Relation senUserId = messageMapper.getDaoId(fromUserName);
            FindVipByOpenId findVipByOpenId = new FindVipByOpenId(info.getUrl(), info.getAccount(),info.getPassword());
            try {
                Vip vip = findVipByOpenId.getData(fromUserName);
                if (null != vip){
                    if(vip.getEmpId() != null) {
                        // String unicode = EmojiUtil.escapeUnicode(content);
                        content = EmojiUtil.filterEmoji(content);
                        String websocket = content.replace("\\","\\\\");
                        String message = "{\"fromUserName\": \"" + fromUserName + "\",\"msgtype\": \"text\", \"text\": {\"content\": \"" + websocket + "\"}}";
                        System.err.println(message);
                        String state = null;
                        try {
                            state = webSocketServer.sendtoUser(message, vip.getEmpId());
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        createTime = formatTime(createTime);

                        //根据openid查询开卡人
                        // findEmployeeByOpenId findEmployeeByOpenId = new findEmployeeByOpenId("59.110.28.94:90", "nea@burgeon.com.cn", "burgeon55321");

                        //   VipAppCode vipAppCode = new VipAppCode("59.110.28.94:90", "nea@burgeon.com.cn", "burgeon55321");

                        if ("0".equals(state)) {
                            //消息存到erp
                            try {
                                //CreteVipCode(fromUserName,"发出",employee.getName(),employee.getId(),state,content);
                                //将消息存到数据库,发送成功
                                //recordMapper.InMessageRecord(fromUserName,vip.getEmpId(),content,createTime,state,vip.getEmpId());
                                //并修改erp状态，加未读消息标志Y
//                                UpVipUnread(fromUserName,"N","发出",state,content,vip,msgType,);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }


                        } else {
                            //recordMapper.InMessageRecord(fromUserName,vip.getEmpId(),content,createTime,state,vip.getEmpId());
                            // 并修改erp状态，加未读消息标志Y
//                            UpVipUnread(fromUserName,"Y","发出",state,content,vip,msgType);


                            // messageMapper.InMessage(content, fromUserName, createTime, senUserId, state);
                            //消息存到erp
//                     try {
//                         Employee employee =findEmployeeByOpenId.getData(fromUserName); //通过友盟推送通知
//                         try {
//                             // Employee employee =findEmployeeByOpenId.getData(fromUserName); //通过友盟推送通知
//                             if(null != employee) {
//                                 UmengUtil umengUtil = new UmengUtil();
//                                 //华为通风道
//                                 String channel = "com.bojun.rfmapplication.activity.home.OrderListActivity";
//                                 //发送消息
//                                  System.err.println("导购的手机号：" + employee.getPhone());
//                                 String extraType = "1";//1是消息
//                                 umengUtil.sendAndroidCustomizedcast(employee.getPhone(), "phone",
//                                         "微信消息", "来自顾客的消息", content, fromUserName, channel, "1");
//
//                             }
//                         } catch (Exception e) {
//                             e.printStackTrace();
//                         }
                            // CreteVipCode(fromUserName,"发出",employee.getName(),employee.getId(),state,content);
                            //System.err.println("没有发送成给");


//                     } catch (Exception e) {
//                         e.printStackTrace();
//                     }



                        }
                    }else {
                        //没有关联的导购，怎么处理
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //System.err.println("导购的ID=="+senUserId);


        }  // 事件推送
        else if ("event".equals(msgType)) { // 事件消息
            // 区分事件推送
            String event = map.get("Event");
            if ("subscribe".equals(event)) { // 订阅事件 或 未关注扫描二维码事件
                // 返回消息时ToUserName的值与FromUserName的互换

                String eventKey = map.get("EventKey");//获取二维码参数，导购id
                //System.err.println(eventKey);
                if(!"".equals(eventKey)) {
                    //1.从二维码获取参数导购的id
                    String daoId = eventKey.split("_")[1];
                    session.setAttribute("daoId",daoId);

                    //System.err.println(daoId);
                    //2.将微信用户和导购关系存入数据库
                    Relation relation = messageMapper.getDaoId(fromUserName);
                    if (relation!=null){

                        messageMapper.upDaoId(relation.getId(),daoId);
                        redisUtil2.set("daoId",daoId);

                    }else {
                        int r = messageMapper.InRelation(fromUserName,daoId);
                        redisUtil2.set("daoId",daoId);
                        //System.err.println(r);
                    }
                    //   int r = messageMapper.InRelation(fromUserName, daoId);


                    //3.修改erp的用户信息


                    //3.将微信用户存到数据库
                    // String accessToken = WeGetAccessToken.getAccessToken();
//                     String accessToken = WeixinUtil.getAccessToken(WeChatInfo.WX_APPID,WeChatInfo.WX_APPSECRET)
//                             .getToken();
//                     //3.2获取微信用户信息
//                     WeiXinUser w = getUserInfo(accessToken, fromUserName);
//                     wxUserMapper.InWxUser(w);
                }

            }  else if ("unsubscribe".equals(event)) { // 取消订阅事件
                //1.删除微信用户表
                //2.删除关系表
                // messageMapper.DeRelation(fromUserName);
                // todo 处理取消订阅事件
            } else if ("SCAN".equals(event)) { // 已关注扫描二维码事件
                //{Ticket=gQHb8DwAAAAAAAAAAS5odHRwOi8vd2VpeGluLnFxLmNvbS9xLzAyYWg3djBFcmhlWUMxY1BIdjF2Y0EAAgSzsBZfAwSAOgkA,
                // CreateTime=1595322848,
                // EventKey=qrscene_111,
                // Event=subscribe,
                // ToUserName=gh_9abc4c76a090,
                // FromUserName=oGxG85v7NY4fqUk2VoCDR6sP-l5g,
                // MsgType=event}
                String eventKey = map.get("EventKey");//是否获取的是消息内容
                //System.err.println("EventKey"+eventKey);
                Relation relation = messageMapper.getDaoId(fromUserName);
                // System.err.println("导购新"+relation.getDaoid());

                //关注用户是否关联导购
                if (relation!=null){

                    messageMapper.upDaoId(relation.getId(),eventKey);
                    redisUtil2.set("daoId",eventKey);

                }else {
                    messageMapper.InRelation(fromUserName,eventKey);
                    redisUtil2.set("daoId",eventKey);
                }


            }else if("VIEW".equals(event)){
                String eventKey = map.get("EventKey");//是否获取的是消息内容
                System.err.println(eventKey);
                System.err.println(session.getAttribute("openID"));
            }
        }

        return responseMessage;
    }





//    /**
//     * 将从安卓获取来的图片发送给微信
//     * @param openId
//     * @throws UnsupportedEncodingException
//     */
//    public void imageAndroid(String openId,String context){
//
//        String accessToken = getAccesToken.GetAccesToken(WeChatInfo.token);
//        WeXinHuiFu.sendTextMessageToUser("有什么事吗？",openId,accessToken);
//
//    }


//    /**
//     * 获取聊天记录
//     * @return
//     */
//
//    public com.alibaba.fastjson.JSONObject getSendCondition(String startTime,String endTime) throws ParseException {
//        //1.获取AccessToken
////        String accessToken = WeGetAccessToken.getAccessToken();
//        //String accessToken = getAccesToken.GetAccesToken(WeChatInfo.token);
//        String access_token = systemService.GetAccesToken(WeChatInfo.token);
//        String url = " https://api.weixin.qq.com/customservice/msgrecord/getmsglist?access_token=ACCESS_TOKEN";
//        url = url.replace("ACCESS_TOKEN", access_token);
//        System.err.println(startTime);
//        System.err.println(endTime);
//
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        Date date = simpleDateFormat.parse(startTime);
//        long sTime = date.getTime()/1000;
//        System.err.println(sTime);
//        Date date1 = simpleDateFormat.parse(endTime);
//        long eTime = date1.getTime()/1000;
//        System.err.println(eTime);
//        String jsonStr = "  {\n" +
//                "      \"starttime\" : "+String.valueOf(sTime)+",\n" +
//                "      \"endtime\" : "+String.valueOf(eTime)+",\n" +
//                "      \"msgid\" : 1,\n" +
//                "      \"number\" : 10000 \n" +
//                "}";
//        com.alibaba.fastjson.JSONObject jsonObject = SendRequest.sendPost(url, jsonStr);
//        jsonObject.get("");
//
//        return jsonObject;
//    }
//


//    public String kefu(){
//
//        TextMessage textMessage = new TextMessage();
//        textMessage.setMsgType(WechatMessageUtil.MESSAGE_TEXT);
//        textMessage.setToUserName(fromUserName);
//        textMessage.setFromUserName(toUserName);
//        textMessage.setCreateTime(System.currentTimeMillis());
//        textMessage.setContent("我已经受到你发来的消息了");
//        responseMessage = WechatMessageUtil.textMessageToXml(textMessage);
//    }




    /**
     * 接受微信发来的消息
     * @param request
     * @return
     */
//    public String processRequest(HttpServletRequest request) throws UnsupportedEncodingException {
//        request.setCharacterEncoding("UTF-8");
//        Map<String, String> map = WechatMessageUtil.xmlToMap(request);
//      //  System.err.println(map);
//        log.info(map);
//        // 发送方帐号（一个OpenID）
//        String fromUserName = map.get("FromUserName");
//
//        // 开发者微信号
//        String toUserName = map.get("ToUserName");
//        // 消息类型
//        String msgType = map.get("MsgType");
//        System.err.println(msgType);
//        // 消息创建时间
//        String createTime =map.get("CreateTime");
//        System.err.println(createTime);
//        // 默认回复一个"success"
//        String responseMessage = "success";
//        // 对消息进行处理
//        if (WechatMessageUtil.MESSAGE_TEXT.equals(msgType)) {// 文本消息
//               String content = map.get("Content");//是否获取的是消息内容
//               System.err.println(content);
//               //将获取的消息存到数据库
//               createTime = formatTime(createTime);
//               System.err.println(createTime);
//              // messageMapper.InMessage(content,fromUserName,createTime);
//               //将消息存到erp
//               TextMessage textMessage = new TextMessage();
//               textMessage.setMsgType(WechatMessageUtil.MESSAGE_TEXT);
//               textMessage.setToUserName(fromUserName);
//               textMessage.setFromUserName(toUserName);
//               textMessage.setCreateTime(System.currentTimeMillis());
//               textMessage.setContent(" ");
//               responseMessage = WechatMessageUtil.textMessageToXml(textMessage);
//               System.err.println(responseMessage);
//
//            return responseMessage;
//
//        }else if (WechatMessageUtil.MESSAtGE_IMAGE.equals(msgType)) {// 图片消息
//            String picUrl = map.get("PicUrl");
//            //将获取的消息存到数据库
//            createTime = formatTime(createTime);
//            System.err.println(createTime);
//          //  messageMapper.InMessage(picUrl,fromUserName,createTime);
//            /*****将消息存到erp，还没做****/
//
//            //回复消息文本，从安卓系统得到回复消息
//            TextMessage textMessage = new TextMessage();
//            textMessage.setMsgType(WechatMessageUtil.MESSAGE_TEXT);
//            textMessage.setToUserName(fromUserName);
//            textMessage.setFromUserName(toUserName);
//            textMessage.setCreateTime(System.currentTimeMillis());
//            textMessage.setContent("我已经受到你发来的图片消息了");
//            responseMessage = WechatMessageUtil.textMessageToXml(textMessage);
//
//            return responseMessage;
//
//        }
//        // 事件推送
//        else if ("event".equals(msgType)) { // 事件消息
//            // 区分事件推送
//            String event = map.get("Event");
//            if ("subscribe".equals(event)) { // 订阅事件 或 未关注扫描二维码事件
//                // 返回消息时ToUserName的值与FromUserName的互换
//                //回复消息文本，从安卓系统得到回复消息
//                TextMessage textMessage = new TextMessage();
//                textMessage.setMsgType(WechatMessageUtil.MESSAGE_TEXT);
//                textMessage.setToUserName(fromUserName);
//                textMessage.setFromUserName(toUserName);
//                textMessage.setCreateTime(System.currentTimeMillis());
//                textMessage.setContent("我已经受到你发来的图片消息了");
//                return responseMessage = WechatMessageUtil.textMessageToXml(textMessage);
////                Map<String, String> returnMap = new HashMap<>();
////                returnMap.put("ToUserName", decryptMap.get("FromUserName"));
////                returnMap.put("FromUserName", decryptMap.get("ToUserName"));
////                returnMap.put("CreateTime", new Date().getTime()+"");
////                returnMap.put("MsgType", "text");
////                returnMap.put("Content", "https://www.baidu.com");
////                String encryptMsg = WXPublicUtils.encryptMsg(WXPayUtils.mapToXml(returnMap), new Date().getTime()+"", WXPublicUtils.getRandomStr());
////                return encryptMsg;
//            }  else if ("unsubscribe".equals(event)) { // 取消订阅事件
//                // todo 处理取消订阅事件
//            } else if ("SCAN".equals(event)) { // 已关注扫描二维码事件
//
//                TextMessage textMessage = new TextMessage();
//                textMessage.setMsgType(WechatMessageUtil.MESSAGE_TEXT);
//                textMessage.setToUserName(fromUserName);
//                textMessage.setFromUserName(toUserName);
//                textMessage.setCreateTime(System.currentTimeMillis());
//                textMessage.setContent("我已经受到你发来的图片消息了");
//                return responseMessage = WechatMessageUtil.textMessageToXml(textMessage);
//
//                // 返回消息时ToUserName的值与FromUserName的互换
////                Map<String, String> returnMap = new HashMap<>();
////                returnMap.put("ToUserName", decryptMap.get("FromUserName"));
////                returnMap.put("FromUserName", decryptMap.get("ToUserName"));
////                returnMap.put("CreateTime", new Date().getTime()+"");
////                returnMap.put("MsgType", "text");
////                returnMap.put("Content", "https://www.baidu.com");
////                String encryptMsg = WXPublicUtils.encryptMsg(WXPayUtils.mapToXml(returnMap), new Date().getTime()+"", WXPublicUtils.getRandomStr());
////                return encryptMsg;
//            }
//        }
//
//
//        log.info("sevice"+responseMessage);
//        return null;
//    }

    /**
     * 将微信消息中的CreateTime转换成标准格式的时间（yyyy-MM-dd HH:mm:ss）
     * @param createTime 消息创建时间
     * @return
     */
    public static String formatTime(String createTime) {

        // 将微信传入的CreateTime转换成long类型，再乘以1000
        long msgCreateTime = Long.parseLong(createTime) * 1000L;

        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        return format.format(new Date(msgCreateTime));

    }


//    public void getAllUsersInfo(){
//        //获取accessToken
//        //String accessToken = WeGetAccessToken.getAccessToken();
//        String accessToken = getAccesToken.GetAccesToken(WeChatInfo.token);
//        //调用获取微信关注的所有用户列表
//       List<String> openIds = getAllWeiXinUser();
//        System.err.println(openIds.size());
//       //获取单个的用户信息
//      // ArrayList<WeiXinUser> WeiXinUsers = new ArrayList<>();
//        for (String openId:openIds) {
//           WeiXinUser weiXinUser = getUserInfo(accessToken,openId);
//            System.err.println("微信"+openId);
//            wxUserMapper.InWxUser(weiXinUser);
//          // WeiXinUsers.add(weiXinUser);
//        }
//        //return WeiXinUsers;
//    }


    /**
     * 获取微信用户的信息
     * @param accessToken
     * @param openId
     * @return
     */
//    @Override
//    public WeiXinUser getUserInfo(String accessToken, String openId) {
//        WeiXinUser weixinUserInfo = null;
//
//        // 上传文件请求路径
//        String action = "https://api.weixin.qq.com/cgi-bin/user/info?access_token="
//                + accessToken+"&openid="+openId;
//        // 拼接获取用户信息接口的请求地址
////        String requestUrl = ProjectConst.GET_WEIXIN_USER_URL.replace("ACCESS_TOKEN", accessToken).replace(
////                "OPENID", openId);
//        // 获取用户信息(返回的是Json格式内容)
//        try {
//            URL urlGet = new URL(action);
//            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
//            http.setRequestMethod("GET"); // 必须是get方式请求
//            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//            http.setDoOutput(true);
//            http.setDoInput(true);
//            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
//            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
//            http.connect();
//            InputStream is = http.getInputStream();
//            int size = is.available();
//            byte[] jsonBytes = new byte[size];
//            is.read(jsonBytes);
//            String result = new String(jsonBytes, "UTF-8");
//
//            JSONObject jsonObject = new JSONObject(result);
//            System.err.println(jsonObject);
//            if (null != jsonObject) {
//                try {
//                    long startTime = System.currentTimeMillis();    //获取开始时间
//                    //封装获取到的用户信息
//                    weixinUserInfo = new WeiXinUser();
//                    weixinUserInfo.setOpenId(jsonObject.getString("subscribe"));
//                    // 用户的标识
//                    weixinUserInfo.setOpenId(jsonObject.getString("openid"));
//                    // 昵称
//                    weixinUserInfo.setNickname(jsonObject.getString("nickname"));
//                    // 用户的性别（1是男性，2是女性，0是未知）
//                    weixinUserInfo.setSex(jsonObject.getInt("sex"));
//                    // 用户所在国家
//                    weixinUserInfo.setCountry(jsonObject.getString("country"));
//                    // 用户所在省份
//                    weixinUserInfo.setProvince(jsonObject.getString("province"));
//                    // 用户所在城市
//                    weixinUserInfo.setCity(jsonObject.getString("city"));
//                    // 用户头像
//                    weixinUserInfo.setHeadImgUrl(jsonObject.getString("headimgurl"));
//                    //OPENID2
//                  //  weixinUserInfo.setHeadImgUrl(jsonObject.getString("OPENID2"));
//                    System.err.println(weixinUserInfo);
//                    long endTime = System.currentTimeMillis();    //获取结束时间
//                    System.out.println("程序运行时间：" + (endTime - startTime) + "ms");    //输出程序运行时间
//                } catch (Exception e) {
//                    if (0== weixinUserInfo.getSubscribe()) {
//                        System.out.println("用户并没有关注本公众号"+jsonObject);
//                    } else {
//                        int errorCode = jsonObject.getInt("errcode");
//                        String errorMsg = jsonObject.getString("errmsg");
//                        System.out.println("由于"+errorCode +"错误码；错误信息为："+errorMsg+"；导致获取用户信息失败");
//                    }
//                }
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//
//        return weixinUserInfo;
//    }

    /**
     * 获取所有的关注用户
     * @return
     */
//    public List<String> getAllWeiXinUser() {
////        GetExistAccessToken getExistAccessToken = GetExistAccessToken.getInstance();
////        String accessToken = getExistAccessToken.getExistAccessToken();
//      //  String accessToken = WeGetAccessToken.getAccessToken();
//        String accessToken = getAccesToken.GetAccesToken(WeChatInfo.token);
//        List<String> openIds = new ArrayList<String>();
//        // 上传文件请求路径
//        String action = "https://api.weixin.qq.com/cgi-bin/user/get?access_token="
//                + accessToken;
//        try {
//            URL urlGet = new URL(action);
//            HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
//            http.setRequestMethod("GET"); // 必须是get方式请求
//            http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//            http.setDoOutput(true);
//            http.setDoInput(true);
//            System.setProperty("sun.net.client.defaultConnectTimeout", "30000");// 连接超时30秒
//            System.setProperty("sun.net.client.defaultReadTimeout", "30000"); // 读取超时30秒
//            http.connect();
//            InputStream is = http.getInputStream();
//            int size = is.available();
//            byte[] jsonBytes = new byte[size];
//            is.read(jsonBytes);
//            String result = new String(jsonBytes, "UTF-8");
//
//            JSONObject jsonObj = new JSONObject(result);
//
//
//            JSONObject json1 = new JSONObject(jsonObj.get("data").toString());
//            System.out.println(json1.toString());
//            JSONArray json2 = new JSONArray(json1.get("openid").toString());
//            for (int i = 0; i < json2.length(); i++) {
//                openIds.add(i, json2.getString(i));
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return openIds;
//    }











//    /***
//     * 获取access_token
//     * @return
//     */
//    public String getAccessToken (){
//        String accessToken;
//        String grantType = "client_credential";
//        String appid = "wxd8fea87570dde770";
//        String secret = "8008eb8f6defa08a1c596af02bf91461";
//        String url = "https://api.weixin.qq.com/cgi-bin/token?" +
//                "grant_type=" + grantType +
//                "&appid=" + appid +
//                "&secret=" + secret;
//        RestTemplate restTemplate = new RestTemplate();
//
//        try {
//            String str = restTemplate.getForObject(url, String.class);
//            System.err.println("str=="+str);
//            accessToken = new JSONObject(str).getString("access_token");
//            System.err.println(accessToken);
//            return accessToken;
//        } catch (JSONException e) {
//            System.err.println("获取access_token失败");
//
//        }
//       return null;
//    }

}
